<template>
    <div>
        <div class="login">
            <div class="log">
                <img :src="systemData.pic" alt=""/>
                <div class="logi">
                    <p class="p1">{{ systemData.brandname }}</p>
                    <p class="p2">{{ systemData.Advertisement }}</p>
                </div>
            </div>
            <div v-if="pageState">
                <div class="inmn">
                    <div class="item ste">
                        <p class="p2 full">中国大陆</p>
                    </div>
                    <div class="item ste">
                        <p class="p2 l">+86</p>
                        <div style="width: 2px;height: 100%;background: #f5f5f5"></div>
                        <input
                                placeholder="请输入手机号码"
                                class="full1"
                                type="number"
                                pattern="[0-9]*"
                                onkeypress="return( /[\d]/.test(String.fromCharCode(event.keyCode) ) )"
                                v-model="phone"
                        />
                        <div class="statecss" v-show="statephone">
                            <p v-text="txtphone"></p>
                            <svg class="icon" aria-hidden="true">
                                <use :xlink:href="stateicon"></use>
                            </svg>
                        </div>
                    </div>
                </div>
                <div class="inmn" style="margin-top: 2vw">
                    <div class="item2">
                        <div class="int">
                            <input placeholder="请输入验证码" pattern="[0-9]*" type="number" v-model="code"/>
                            <div class="statecss" v-show="statecode">
                                <p v-text="txtcode"></p>
                                <svg class="icon" aria-hidden="true">
                                    <use :xlink:href="stateicon2"></use>
                                </svg>
                            </div>
                        </div>
                        <div class="r">
                            <p class="p4" :class="" @click="getCode">{{ codetxt }}</p>
                        </div>
                    </div>
                </div>
            </div>
            <div v-else>
                <div class="inmn">
                    <div class="item ste">
                        <p class="p2 l">输入密码</p>
                        <div style="width: 2px;height: 100%;background: #f5f5f5"></div>
                        <input placeholder="6-16位字母与数字的组合"
                               class="full1"
                               type="password"
                               v-model="password"
                               @blur="isPass"/></div>
                    <div class="item ste">
                        <p class="p2 l">确认密码</p>
                        <div style="width: 2px;height: 100%;background: #f5f5f5"></div>
                        <input placeholder="6-16位字母与数字的组合"
                               class="full1"
                               type="password"
                               v-model="passwordSure"
                               @blur="isPass2"/>
                    </div>
                </div>
            </div>
            <div class="mi-ste">
                <div class="statecs2" v-show="statepass">
                    <p>不一致</p>
                    <svg class="icon" aria-hidden="true">
                        <use :xlink:href="stateicon"></use>
                    </svg>
                </div>
            </div>
            <div class="btn-db">
                <button-normal
                        widthPro="200"
                        heightPro="35"
                        :textBtn="textBtn"
                        color="#fff"
                        size="14"
                        @click.native="sure"
                        v-show="hidshow"
                ></button-normal>
            </div>
        </div>
    </div>
</template>

<script>
    import API from '../request/api';
    import {Toast} from 'vant';
    import buttonNormal from '@/components/common/buttonNormal';
    import ButtonNormalHollow from '@/components/common/buttonNormalHollow';
    import {sysMixin, commonMixin} from '@/common/mixin';
    import regular from '@/common/regular';
    import {debounce} from '@/common/utils';

    export default {
        name: 'register',
        components: {ButtonNormalHollow, buttonNormal},
        mixins: [sysMixin, commonMixin],
        data() {
            return {
                dealshow: false,
                phone: '',
                code: '',
                password: '', // 密码
                passwordSure: '', //密码确认
                stateicon: '#icon-dui',
                stateicon2: '#icon-dui',
                txtphone: '', // 手机号校验文本
                statephone: false, //手机号是否不对，true为不正确
                codetxt: '获取', // 验证码校验文本
                txtcode: '', // 验证码校验文本
                statecode: false, //验证码是否不对，true为不正确
                stateSendCode: true,
                pageState: true, // 是否是注册的第一种状态，校验手机号验证码
                statepass: false, //密码是否不一致，true为不一致
                textBtn: '下一步', // 按钮文本
                isagent: 0,
                docmHeight: '0', //默认屏幕高度
                showHeight: '0', //实时屏幕高度
                hidshow: true, //显示或者隐藏footer,
                isResize: false, //默认屏幕高度是否已获取
                stateCall: false, //手机号是否可以用
            };
        },
        created() {
            this.$watch(
                'phone',
                debounce((newVal) => {
                    this.checkPhone();
                }, 20)
            );
        },
        mounted() {
            window.onresize = () => {
                return (() => {
                    if (!this.isResize) {
                        //  //默认屏幕高度
                        this.docmHeight = document.body.clientHeight;
                        this.isResize = true;
                    }
                    //     //实时屏幕高度
                    this.showHeight = document.documentElement.clientHeight;
                })();
            };
            window.addEventListener('focusout', () => {
                window.scrollTo(0, 0);
            });
        },
        computed: {
            checkIcon() {
                return this.isagent === 0 ? '#icon-dui' : '#icon-dui';
            }
        },
        watch: {
            passwordSure() {
                // 密码确认
                let regu = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/;
                if (!regu.test(this.passwordSure) && this.passwordSure !== this.password) {
                    this.stateicon = '#icon-cuo';
                    this.statepass = true;
                } else if (this.passwordSure === this.password) {
                    this.statepass = false;
                }
            },
            showHeight() {
                // alert(this.docmHeight + this.showHeight);
                if (this.docmHeight > this.showHeight) {
                    this.hidshow = false;
                } else {
                    console.log('small');
                    this.hidshow = true;
                }
            }
        },
        methods: {
            checkPhone() {
                if (!regular.REGEX_CHINA_MOBILE.test(this.phone)) {
                    this.txtphone = '手机号不正确';
                    this.stateicon = '#icon-cuo';
                    this.statephone = true;
                } else {
                    this.request.get(API.polyCheckPhone, {phone: this.phone}).then((res) => {
                        if (!res) {
                            // 可以注册
                            this.stateCall = true;
                            this.txtphone = '可以使用';
                            this.stateicon = '#icon-dui';
                        } else {
                            //    已注册
                            this.stateCall = false;
                            this.txtphone = '已注册';
                            this.stateicon = '#icon-cuo';
                        }
                        this.statephone = true;
                    });

                    // this.stateSendCode = true;
                }
            },
            isPass() {
                //    密码校验
                let regu = /^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]{6,16}$/;
                if (!regu.test(this.password)) {
                    Toast('密码格式不规范');
                    this.password = '';
                }
            },
            isPass2() {
                //    密码校验
                let regu = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/;
                if (!regu.test(this.passwordSure)) {
                    Toast('密码格式不规范');
                    this.passwordSure = '';
                }
            },
            async sure() {
                if (this.textBtn == '下一步') {
                    if (!this.phone) {
                        Toast('请先填写手机号');
                    } else if (!this.stateCall) {
                        Toast('该手机号已注册');
                    } else if (!this.code || this.stateSendCode) {
                        Toast('请先获取并填写验证码');
                    } else {
                        // 至验证短信吗
                        if (await this.selectCode()) {
                            this.pageState = false;
                            this.textBtn = '注册';
                        }
                    }
                } else {
                    if (this.passwordSure === this.password && this.password !== '') {
                        let data = {
                            phone: this.phone,
                            code: this.code,
                            password: this.password,
                            referrer: this.$store.state.login.refer.referid,
                            system: this.$store.state.login.system,
                            isagent: this.isagent
                        };
                        this.request.post(API.polyRegister, data).then(
                            (res) => {
                                // 返回的数据直接登录了
                                this.$store.commit('setToken', res.token); // 本地存token
                                this.$store.commit('setTokenType', res.token_type || '1');
                                this.$store.commit('system', res.system); // 本地存token过期时间
                                // 然后获取userInfo
                                this._getPolyInfo();
                            }
                        ).catch((err) => {
                            console.log(err);
                            this.$toast.fail(err);
                        });
                    }
                }
            },
            //聚合帐号info
            _getPolyInfo() {
                return this.request
                    .get(API.polyInfo, {aid: this.aid})
                    .then((res) => {
                        this.$store.commit('setUserInfo', res);
                        //隐藏登录组件
                        this.$store.commit('loginShow', false);
                        //  更新tokenArray
                        let tokenArray = JSON.parse(localStorage.getItem('tokenArray'));
                        if (tokenArray) {
                            // 原来有就更新
                            tokenArray[this.system] = {token: this.token, userInfo: res};
                            this.$store.commit('setTokenArray', tokenArray);
                        } else {
                            // 没有就新建本地tokenArray
                            let tokenArrayFirst = {};
                            tokenArrayFirst[this.system] = {token: this.token, userInfo: res};
                            this.$store.commit('setTokenArray', tokenArrayFirst);
                        }
                        //聚合登录直接进入account页面
                        this.$router.replace({
                            name: 'poly-account',
                            query: {
                                isLogin: true
                            }
                        });
                    })
                    .catch((err) => {
                        console.log(err);
                        this.$toast.fail(err);
                    });
            },
            deal() {
                this.dealshow = true;
            },
            getCode() {
                if (!this.phone || this.txtphone === '手机号不正确') {
                    Toast('请先填写手机号');
                } else if (!this.stateCall) {
                    Toast('该手机号已注册不能再次注册');
                } else {
                    let data = {
                        phone: this.phone,
                        type: 9 //注册聚合帐号
                    };
                    if (this.stateSendCode) {
                        this.request.post(API.getCode, data).then((res) => {
                            //    验证码发送成功
                            this.stateSendCode = false;
                            this.setTime();
                        });
                    }
                }
            },
            setTime() {
                //    倒计时
                let demo = 70;
                this.codetxt = demo;
                let setTer = setInterval(() => {
                    if (demo > 0) {
                        this.codetxt = demo;
                        demo--;
                    } else {
                        clearInterval(setTer);
                        this.codetxt = '获取';
                        this.stateSendCode = true;
                        this.txtphone = '';
                    }
                }, 1000);
            },
            checkAgent() {
                //    代理商同步
                if (this.isagent === 0) {
                    this.isagent = 1;
                } else {
                    this.isagent = 0;
                }
            },
            selectCode() {
                // 校验验证码正确
                return this.request.post(API.checkCode, {type: 9, code: this.code, phone: this.phone}).then((res) => {
                    if (res.status == 1) {
                        // 正确
                        return true;
                    } else if (res.status == 0) {
                        Toast('验证码错误');
                        return false;
                    }
                });
            }
        }
    };
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
    @import '~assets/main.styl'
    .login {
        position relative
        box-sizing border-box
        /*height 100vh*/
        background #f5f5f5
        width 100vw

        .log {
            height 30vw
            flex-x(center)
            padding-top 12vh

            img {
                width vw(66)
            }

            .logi {
                height 12vw
                flex-y(space-between, flex-start)
                padding-left 3vw
            }
        }

        .inmn {
            flex-y()
            margin 0 vw(15)
            border-radius main-radius
            background grayF

            .item {
                width 100%
                height vw(55)
                flex-x()

                .l {
                    flex 1.5
                    text-align center
                }

                .r {
                    flex 4
                    padding-left 20vw
                    box-sizing border-box
                }

                .full {
                    flex 1
                    text-align center
                    line-height vw(55)
                }

                .fullp {
                    flex 1
                    text-align center
                    line-height vw(55)
                }

                .full1 {
                    flex 4
                    text-align left
                    height vw(25)
                    padding vw(10) 0 vw(10) vw(60)
                }

                .statecss {
                    position absolute
                    right vw(30)
                    flex-x()

                    .icon {
                        margin-left vw(15)
                        fill main-color
                    }

                    p {
                        word-vw(word14, main-color)
                    }
                }
            }

            .ste {
                border-bottom 1px solid gray5
            }

            .item2 {
                flex-x(space-between)
                height vw(55)
                flex-x()
                width 100%

                .int {
                    flex 4
                    flex-x()
                    padding-left vw(15)

                    input {
                        height vw(55)
                    }
                }

                .r {
                    flex 1
                    background main-color
                    border-radius 0 main-radius main-radius 0
                    height vw(55)
                    flex-x(center)
                }
            }
        }

        .mi-ste {
            padding 0 4vw
            flex-x(flex-end)
            height vw(24)

            .statecs2 {
                width 18vw
                flex-x(flex-end)
                right 3vw

                .icon {
                    margin-left vw(8)
                    fill main-color
                }

                p {
                    word-vw(word14, main-color)
                }
            }
        }

        .txt {
            flex-x(space-between)
            padding 0 vw(15)
            margin-top 4vw

            p {
                line-height vw(28)
                word-vw(word10, main-color)
            }
        }

        .txt1 {
            flex-x(space-between)
            padding 0 vw(15)

            p {
                line-height vw(28)
            }
        }

        .btn-db {
            position fixed
            background white
            width 100vw
            bottom 0
        }

        .close {
            fill gray3
            position absolute
            right vw(20)
            arrow()
            top vw(20)
        }

        .fullInput {
            height vw(50)
            line-height vw(50)
            border-bottom 1px solid #efefef
            display flex
            justify-content space-between
            width 100%

            .pic {
                fill main-color
                width vw(20)
                height vw(20)
            }

            input {
                width 70%
            }
        }
        input:

        :placeholder {
            color gray9
        }

        .agree {
            height vw(50)
            line-height vw(50)
            display: flex;
            align-items: center;
            position relative
            color gray9

            .circle {
                border 1px solid gray6
                border-radius 50%
                width vw(15)
                height vw(15)
                box-sizing border-box
                margin-right vw(15)
            }

            .select {
                width vw(16)
                height vw(16)
                position absolute
                fill main-color
            }

            span {
                color gray3
            }
        }

        .sync {
            flex-x()
            padding 0 4vw
            margin-top 3vw
            height 10vw

            .sync-1 {
                .p1 {
                    word-vw(word14, gray3)
                    line-height 2
                }

                .p2 {
                    word-vw(word10, gray9)
                }
            }

            .icon {
                width vw(20)
                height vw(20)
            }
        }
    }

    .sure {
        background-color main-color
        position relative
        width 100vw
        text-align center
        height vw(50)
        line-height vw(50)
        left 0
        color grayF
    }
</style>
